<template>
    <div class="login-container">
        <div class="back-home">
            <el-button type="text" @click="goHome">
                <el-icon><ArrowLeft /></el-icon>
                返回首页
            </el-button>
        </div>
        <div class="background">
            <div class="gradient"></div>
            <div class="particles">
                <div v-for="i in 50" :key="i" class="particle" :style="{
                    left: `${Math.random() * 100}%`,
                    top: `${Math.random() * 100}%`,
                    animationDelay: `${Math.random() * 5}s`
                }"></div>
            </div>
        </div>
        <div class="login-content">
            <h2>抖阳统一身份认证</h2>
            <el-form :model="loginForm">
                <el-form-item>
                    <div class="input-wrapper">
                        <el-input 
                            v-model="loginForm.userName" 
                            class="custom-input"
                            @focus="handleFocus('userName')"
                            @blur="handleBlur('userName')"
                            autocomplete="off"
                        >
                            <template #prefix>
                                <span class="floating-label" :class="{ 'active': isFocused.userName || loginForm.userName }">用户名</span>
                            </template>
                        </el-input>
                    </div>
                </el-form-item>
                <el-form-item>
                    <div class="input-wrapper">
                        <el-input 
                            v-model="loginForm.password" 
                            type="password" 
                            class="custom-input"
                            @focus="handleFocus('password')"
                            @blur="handleBlur('password')"
                        >
                            <template #prefix>
                                <span class="floating-label" :class="{ 'active': isFocused.password || loginForm.password }">密码</span>
                            </template>
                        </el-input>
                    </div>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleLogin" :loading="loading" class="login-button">登录</el-button>
                </el-form-item>
            </el-form>
        </div>

        <!-- 授权确认对话框 -->
        <el-dialog
            v-model="showAuthDialog"
            title="检测到已登录，请授权确认"
            width="500px"
            :close-on-click-modal="false"
            :show-close="false"
            class="auth-dialog"
        >
            <div class="auth-content">
                <div class="app-info">
                    <img :src="address.minioUrl + 'image/' + appInfo?.clientLogo" class="app-logo" />
                    <div class="app-name">{{ appInfo?.clientName }}</div>
                    <p>{{hostName}} </p>
                </div>
                <div class="auth-text">
                    <p>请求访问您的以下信息：</p>
                    <ul class="scope-list">
                        <li v-for="scope in appInfo?.scopes" :key="scope">
                            <el-icon><Check /></el-icon>
                            <span>{{ scope }}</span>
                        </li>
                    </ul>
                </div>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleAuthReject">拒绝</el-button>
                    <el-button type="primary" @click="handleAuthConfirm" :loading="loading">
                        同意授权
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import request from '@/base/request'
import {address} from '@/base/address'
import AppInfo from '@/types/auth/AppInfo'

const router = useRouter()
const route = useRoute()
const loading = ref(false)
const showAuthDialog = ref(false)
const backUrl = route.query.backUrl as string
const redirect = route.query.redirect as string
const url = new URL(redirect);
const hostName = `${url.protocol}//${url.hostname}`;


let html=document.documentElement
html.className='dark'

// 应用信息
const appInfo = ref<AppInfo>()

const loginForm = ref({
    userName: '',
    password: ''
})

const isFocused = ref({
    userName: false,
    password: false
})

const handleFocus = (field: string) => {
    isFocused.value[field] = true
}

const handleBlur = (field: string) => {
    if (!loginForm.value[field]) {
        isFocused.value[field] = false
    }
}

// 返回首页
const goHome = () => {
    window.location.href = address.homeUrl
}

// 获取应用信息
const getAppInfo=async()=>{
    const response=await request.get(`/user/oauth2/getAppInfo?hostName=${hostName}`)
    if(response.data.code===200){
        appInfo.value=response.data.data
        checkLogin()
    }else{
        ElMessage.error(response.data.msg)
    }
}

// 处理登录
const handleLogin = async () => {
    if (!loginForm.value.userName) {
        ElMessage.error('请输入用户名')
        return
    }
    if (!loginForm.value.password) {
        ElMessage.error('请输入密码')
        return
    }
    
    loading.value = true
    try {
        const response = await request.post('/user/oauth2/doLogin', loginForm.value)
        if (response.data.code === 200) {
            // 登录成功，显示授权对话框
            showAuthDialog.value = true
            document.cookie = `${response.data.data}; path=/auth/login/`;
        } else {
            ElMessage.error(response.data.msg)
        }
    } catch (error) {
        console.log(error)
        ElMessage.error('登录失败，请重试')
    } finally {
        loading.value = false
    }
}

// 处理授权确认
const handleAuthConfirm = async () => {
    loading.value = true
    try {
        const ticketResponse = await request.get(`${address.oauth2Url}/user/oauth2/authorize`,{
            params:{
                client_id:appInfo.value?.id,
                redirect_uri:hostName,
                response_type:'code',
            }
        })
        if (ticketResponse.data.code === 200) {
            const code = ticketResponse.data.data
            
            // 跳转到回调地址并携带ticket
            window.location.href = `${redirect}?code=${code}&backUrl=${backUrl}`
        } else {
            ElMessage.error('获取授权失败')
        }
    } catch (error) {
        ElMessage.error('授权失败，请重试')
    } finally {
        loading.value = false
    }
}

// 处理授权拒绝
const handleAuthReject = () => {
    showAuthDialog.value = false
    ElMessage.info('已拒绝授权')
}

const checkLogin=async()=>{
    const response=await request.get('/user/oauth2/checkLogin')
    if(response.data.code===200 && response.data.data){
        showAuthDialog.value=true
    }
}



onMounted(() => {
    if(!backUrl || backUrl.length === 0 || !hostName || hostName.length === 0){
        ElMessage.error('参数错误')
        window.location.href = address.homeUrl
    }
    getAppInfo()
})

</script>

<style scoped>
.login-container {
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    overflow: hidden;
}

.background {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 1;
}

.gradient {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: linear-gradient(135deg, #1a1a1a 0%, #2d2d2d 100%);
}

.particles {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

.particle {
    position: absolute;
    width: 4px;
    height: 4px;
    background: rgba(255, 255, 255, 0.5);
    border-radius: 50%;
    animation: float 15s infinite linear;
}

@keyframes float {
    0% {
        transform: translateY(0) translateX(0);
        opacity: 0;
    }
    10% {
        opacity: 1;
    }
    90% {
        opacity: 1;
    }
    100% {
        transform: translateY(-100vh) translateX(100px);
        opacity: 0;
    }
}

.login-content {
    width: 100%;
    max-width: 1200px;
    padding: 0 20px;
    z-index: 2;
}

h2 {
    text-align: center;
    margin-bottom: 40px;
    color: #fff;
    font-size: 32px;
    font-weight: 300;
    text-shadow: 0 0 10px rgba(255, 255, 255, 0.5);
}

.input-wrapper {
    position: relative;
    margin-bottom: 30px;
    width: 100%;
}

:deep(.custom-input) {
    width: 50%;
    height: 60px;
    margin-left: 25%;
}

:deep(.custom-input .el-input__wrapper) {
    background: transparent !important;
    box-shadow: none !important;
    border: none !important;
    border-bottom: 2px solid rgba(255, 255, 255, 0.3) !important;
    border-radius: 0 !important;
    transition: all 0.3s ease;
    padding: 0 !important;
}

:deep(.custom-input .el-input__wrapper:hover) {
    border-bottom-color: rgba(255, 255, 255, 0.5) !important;
}

:deep(.custom-input .el-input__wrapper.is-focus) {
    border-bottom-color: #2196F3 !important;
}

:deep(.custom-input .el-input__inner) {
    height: 60px;
    line-height: 60px;
    font-size: 18px;
    color: #fff !important;
    padding-left: 0 !important;
}

.floating-label {
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    color: rgba(255, 255, 255, 0.6);
    font-size: 18px;
    transition: all 0.3s ease;
    pointer-events: none;
}

.floating-label.active {
    top: -10px;
    color: #2196F3;
}

:deep(.custom-input .el-input__prefix) {
    padding-left: 0;
    margin-right: 0;
}

.login-button {
    width: 20%;
    height: 50px;
    font-size: 16px;
    border-radius: 80px;
    background: linear-gradient(45deg, #2196F3, #21CBF3) !important;
    border: none !important;
    box-shadow: 0 4px 15px rgba(33, 203, 243, 0.3) !important;
    transition: all 0.3s ease;
    margin-left:40%;
}

.login-button:hover {
    background: linear-gradient(45deg, #1976D2, #1E88E5) !important;
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(33, 203, 243, 0.4) !important;
}

.auth-content {
    text-align: center;
    position: relative;
}

.app-info {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 30px;
    position: relative;
}

.app-logo {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    margin-bottom: 15px;
    box-shadow: 0 0 20px rgba(33, 150, 243, 0.3);
    border: 2px solid rgba(255, 255, 255, 0.2);
    backdrop-filter: blur(5px);
}

.app-name {
    color: #fff;
    font-size: 24px;
    font-weight: 500;
    text-shadow: 0 0 10px rgba(255, 255, 255, 0.3);
}

.auth-text {
    color: rgba(255, 255, 255, 0.8);
    margin-bottom: 20px;
    text-shadow: 0 0 5px rgba(255, 255, 255, 0.2);
}

.scope-list {
    list-style: none;
    padding: 0;
    margin: 0;
}

.scope-list li {
    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
    margin-bottom: 10px;
    padding: 8px 20px;
    border-radius: 8px;
    border: 1px solid rgba(255, 255, 255, 0.1);
    transition: all 0.3s ease;
}

.scope-list li:hover {
    background: rgba(0, 0, 0, 0.4);
    transform: translateX(5px);
}

.scope-list li .el-icon {
    color: #21CBF3;
    margin-right: 10px;
    font-size: 18px;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 20px;
}

.back-home {
    position: absolute;
    top: 20px;
    left: 20px;
    z-index: 3;
}

.back-home .el-button {
    color: #fff;
    font-size: 16px;
    padding: 8px 16px;
    background: transparent;
    border-radius: 20px;
    transition: all 0.3s ease;
}

.back-home .el-button:hover {
    color: #2196F3;
    transform: translateX(-5px);
}

.back-home .el-icon {
    margin-right: 5px;
    font-size: 18px;
}

</style>